<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/03/11
 * Time: 12:38
 * @link http://www.lmterp.cn
 */

namespace app\command;

use app\common\model\Orders;
use think\console\input\Option;
use think\facade\Log;

/**
 * 订单选择渠道
 * Class OrderChannel
 * @package app\command
 */
class OrderChannel extends BaseCommand
{
    protected function configure()
    {
        $this->setName('order_channel')
            ->addOption("start_date", null, Option::VALUE_REQUIRED, "开始导入时间，默认为今天")
            ->addOption("end_date", null, Option::VALUE_REQUIRED, "结束导入时间")
            ->addOption("ids", null, Option::VALUE_REQUIRED, "订单id，多个使用英文逗号分开");
    }

    /**
     * 执行选择渠道
     * @date 2021/03/11
     * @author longli
     */
    protected function handler()
    {
        $orders = Orders::with(['detail'])
            ->where('channel_id', 0);
        if($this->input->hasOption('ids'))
        {
            $orders->whereIn("order_id", replaceStr($this->input->getOption('ids')));
        }
        else
        {
            // 处理时间范围
            $startDate = $this->input->hasOption('start_date')
                ? $this->input->getOption('start_date')
                : date('Y-m-d');
            $endDate = $this->input->hasOption('end_date')
                ? $this->input->getOption('end_date')
                : date('Y-m-d', strtotime("1day"));
            $orders->where([
                ['create_time', 'egt', $startDate],
                ['create_time', 'elt', $endDate]
            ]);
        }
        Log::info('订单开始选择渠道');
        $orders->chunk($this->defChunk, function($orders)
        {
            foreach($orders as $order)
            {
                if($chId = $this->getChannelByOrder($order))
                {
                    $order->channel_id = $chId;
                    $order->save();
                }
            }
        });
        Log::info('订单完成选择渠道');
    }

    /**
     * 通过订单获取渠道 id
     * @param Orders $order
     * @date 2021/03/11
     * @author longli
     */
    protected function getChannelByOrder(Orders $order)
    {
        $chId = 0;
        // @todo 未完成渠道选择
        return $chId;
    }
}
